package com.aegis.autodeployplugin;

import com.aegis.autodeployplugin.entity.extension.UploadExtension;
import com.aegis.autodeployplugin.tasks.NotifyTask;
import com.aegis.autodeployplugin.tasks.PgyUploadTask;
import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;

import org.apache.http.util.TextUtils;
import org.gradle.api.Action;
import org.gradle.api.DomainObjectSet;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;

public class AutoDeployPlugin implements Plugin<Project> {
    public static final String PLUGIN_EXTENSION_NAME = "uploadAutoDeploy";
    public static final String APP_EXTENSION_NAME = "android";
    public static final String APP_UPLOAD_RELEASE_NAME = "uploadRelease";

    @Override
    public void apply(Project project) {
        UploadExtension uploadConfig = project.getExtensions().create(PLUGIN_EXTENSION_NAME, UploadExtension.class);
        project.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
                AppExtension appExtension = (AppExtension) project.getExtensions().findByName(APP_EXTENSION_NAME);
                if (TextUtils.isEmpty(uploadConfig.pgyApiKey)){
                    throw new GradleException("蒲公英 apiKey 配置不正确，请检查 build.gradle 配置");
                }

                DomainObjectSet<ApplicationVariant> appVariants = appExtension.getApplicationVariants();
                for (ApplicationVariant variant : appVariants){
                    // 遍历 buildTypes ， 当存在 uploadRelease 时，创建 加固 和 蒲公英上传任务
                    if (variant.getBuildType().getName().equalsIgnoreCase(APP_UPLOAD_RELEASE_NAME)){
                        // 修正 task 名称为 驼峰命名
                        String variantName = variant.getName().substring(0, 1).toUpperCase() + variant.getName().substring(1);

                        // 创建上传 task
                        PgyUploadTask uploadTask = project.getTasks().create("autoUpload" + variantName, PgyUploadTask.class);
                        uploadTask.init(uploadConfig, variant);

                        // 创建通知 task
                        NotifyTask notifyTask = project.getTasks().create("autoUploadAndNotify" + variantName, NotifyTask.class);
                        notifyTask.init(uploadConfig);

                        // 编译前，先调用 clean task
                        Task cleanTask = project.getTasks().findByName("clean");
                        variant.getAssembleProvider().get().dependsOn(cleanTask);
                        // 上传依赖 apk打包 task
                        uploadTask.dependsOn(variant.getAssembleProvider().get());
                        // 通知依赖 上传完成 task
                        notifyTask.dependsOn(uploadTask);
                    }
                }
            }
        });
    }
}